#专门对validate_en.js文件进行解析

import execjs,xlwt
import json,re,os,time
from conf.setting import special_mark
#特殊的专门写validate_en.js数据进xls
'''参数说明
参数1 ： 要写进表格中的最后一行的行数
参数2 ： validate_en.js文件地址
参数3 ： 该英语对应翻译文件的地址
参数4 ： 写入数据表的地址
参数5 ： 文件的名称
'''
def special_write_xls(write_row,file1,file2,sheet1,filename):
    ret_data1 = file2json(file1)  #读en源文件中的数据
    ret_data2 = file2json(file2)  #读所选择的语言的数据

    #print(ret_data1)
    for key1 in ret_data1: 
        write_row +=1
        
        sheet1.write(write_row,0,key1)   #key
        
        if type(ret_data1[key1]) ==list: #如果是数组，则将值用,连接
            value1 = ','.join(ret_data1[key1])
            sheet1.write(write_row,1,value1) #key对应语言值
            sheet1.write(write_row,5,'list') #key对应语言值
        else:
            if '{$jQuery}' in ret_data1[key1]:
                value1 = ret_data1[key1].replace('{$jQuery}','')
                sheet1.write(write_row,1,value1)
                sheet1.write(write_row,4,'mark')  #写是否有{$jQuery}标记
            else:
                sheet1.write(write_row,1,ret_data1[key1])  #key对应的英语值

        #查找特殊标记的个数
        num = 0
        for mark in special_mark:
            data_tmp = ''
            if type(ret_data1[key1]) ==list:
                data_tmp = ','.join(ret_data1[key1])
            else:
                data_tmp = ret_data1[key1]
            num += len(re.findall(mark,str(data_tmp)))
        sheet1.write(write_row,6,num)

        if not ret_data2== False:
            if key1 in ret_data2:
                if type(ret_data1[key1]) ==list: #如果是数组，则将值用,连接
                    value2 = ','.join(ret_data2[key1])
                    sheet1.write(write_row,2,value2) #key对应语言值
                else:
                    if '{$jQuery}' in ret_data2[key1]:
                        value1 = ret_data2[key1].replace('{$jQuery}','')
                        sheet1.write(write_row,2,value1)
                    else:
                        sheet1.write(write_row,2,ret_data2[key1]) #key对应语言值
            else:
                pass
                #sheet1.write(write_row,2,'')
        else:
            pass
            #sheet1.write(write_row,1,'')
        sheet1.write(write_row,3,filename)  #写文件名
    return write_row


#参数为文件地址
#读取validate_文件内容
def file2json(file_dir):
    #判断file_dir文件是否
    if not os.path.exists(file_dir):
        return False
    with open(file_dir,'r',encoding='utf-8')  as f0:
        ret_data = f0.read()
        ret_data = re.findall('=\s*({[\s\S]*})',ret_data)
        ret_data = ret_data[0].split('\n')

        colle_data = ''
        for i,line in enumerate(ret_data):
            line = line.strip()
            re_match = re.findall('([^\s]*)\s*:\s*jQuery.validator.format\((.*)\)',line)
            #print(re_match) #[('maxlength', '"Please enter no more than {0} characters."')]
            if re_match:
                key = re_match[0][0]  
                value = re_match[0][1]
                value += "+'{$jQuery}'" #增加{$jQuery}占位符，将来需要还原为jQuery.validator.format
                if(i ==len(ret_data)-2):  #减二是因为还有}符号占行
                    line = key + ':' + value
                else:
                    line = key + ':' + value + ','
            colle_data += line
        
        ret_data = execjs.get(execjs.runtime_names.JScript).eval(colle_data)
        #print(ret_data)
        return ret_data



#写特殊的validate_en.js文件
'''
参数1：英语对照文件的地址
参数2：要写入文件的地址
参数3：要写入文件的数
'''
def special_write_js(file1_dir,file2_dir,data):
    ret_data1 = file2json(file1_dir)
    #print(ret_data1,type(ret_data1))
    #首先判断两个对象的key数量是否相等
    if not (len(ret_data1) == len(data) ):
        err_message = 'The number of key-value pairs is incorrect,please check table.'
        write_err_log(err_message)
        return

    #判断表格中的key是否都与原英语文件中的key相同
    tmp_obj={}  #重新存储key_value形式对象
    for item in data:
        #item 类型变为了str
        item = json.loads(item)
        key = item['key']
        value1 = item['value1']
        value2 = item['value2']
        if value1 == 'false':
            value1 = False
        if value2 == 'false':
            value2 = False
        phpnameOtrue = item['phpnameOtrue']

        tmp_obj[key] = value2
        if key in ret_data1: #有key相等
            pass
        else:
            err_message = 'key:%s is not in source file:%s.' % (key,ori_filename)
            write_err_log(err_message)
            return
        #判断英语翻译是否改动
        # 暂时没做
        
    #先将数据写到一个零时文件里
    tmp_txt=os.path.join(os.path.dirname(os.path.abspath(__file__)),'validate_tmp.txt')
    with open(tmp_txt,'w',encoding='utf-8') as f0:
        f0.write('\n')
        for index,item in enumerate(data):
            item = json.loads(item)
            key = item['key']
            value = item['value2']  #翻译
            if value == 'false':
                value = False
            phpnameOtrue = item['phpnameOtrue']
            if phpnameOtrue == 'mark':  #有标记
                key_val = key + ' : ' +'"' +value +'"'
                if index == len(data)-1:
                    f0.write('\t'+key_val +'\n')
                else:
                    f0.write('\t'+key_val +',\n')
            else:  #无标记
                key_val = key + ' : ' +'jQuery.validator.format("' +value +'")'
                if index == len(data)-1:
                    f0.write('\t'+key_val +'\n')
                else:
                    f0.write('\t'+key_val +',\n')

    #写完后读取文件内容   
    with open(tmp_txt,'r',encoding='utf-8') as f0:
        tmp_txt_data = f0.read()
        #print(tmp_txt_data)

    #通过检验,现在可以写数据进文件了
    with open(file1_dir,'r',encoding='utf-8') as f0:
        file_data0 = f0.read()
        match_data = re.findall('{([\s\S]*)};',file_data0)
        match_data = match_data[0]
        
        write_data = file_data0.replace(match_data,tmp_txt_data)
        #写数据进文件
        with open(file2_dir,'w',encoding='utf-8') as f1:
            f1.write(write_data)
    
    #删除临时文件
    if os.path.exists(tmp_txt):
        os.remove(tmp_txt)
    
    return True
    
    


#写错误日志函数
def write_err_log(err_message):
    print('>>error:'+err_message)
    print('please check your .xls file'.center(50,'-'))
    #日志目录
    logAddr = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),'logs')
    log_filename = os.path.join(logAddr,time.strftime('%Y_%m_%d',time.localtime())+'.log')
    with open(log_filename, 'a',encoding='utf-8') as fo:
        time1 = time.strftime('%H:%M:%S ',time.localtime())
        fo.write(time1+err_message + os.linesep)

